/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved.
 */

package com.device.idea.demo.view.widget;

import android.content.Context;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

import androidx.annotation.NonNull;

import com.device.idea.demo.constant.ToolbarPosition;
import com.device.idea.demo.util.LogUtil;

/**
 * 基于工具栏的悬浮窗基类
 * 生命周期：new -> onCreateContentView -> show -> initViewStatus -> show ... -> show -> dismiss
 *
 * @since 2021-04-13
 */
public abstract class BaseToolbarPopupWindow extends BaseUiPopupWindow {
    /**
     * 是否初始化View的数据
     */
    private boolean isInitViewData = false;

    /**
     * 构造方法
     *
     * @param context 上下文对象
     */
    public BaseToolbarPopupWindow(@NonNull Context context) {
        super(context, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
    }

    /**
     * 构造方法
     *
     * @param context 上下文对象
     * @param width popupWindow的宽
     * @param height popupWindow的高
     * @param isTouchable true-触摸popupWindow外部会消失
     */
    public BaseToolbarPopupWindow(@NonNull Context context, int width, int height, boolean isTouchable) {
        super(context, width, height, isTouchable);
    }

    @Override
    public void show(@NonNull View anchorView, @NonNull ToolbarPosition toolbarPosition) {
        LogUtil.info(getTag(), "toolbarPosition =" + toolbarPosition.toString());
        showAndUpdateView(anchorView, toolbarPosition, 0, 0);
    }

    /**
     * 显示工具栏子菜单悬浮窗，并更新悬浮窗内容
     *
     * @param anchorView 锚点视图
     * @param toolbarPosition 工具栏位置
     * @param offsetX x轴方向偏移
     * @param offsetY y轴方向偏移
     */
    protected void showAndUpdateView(@NonNull View anchorView, @NonNull ToolbarPosition toolbarPosition, int offsetX,
        int offsetY) {
        showAtAnchorView(anchorView, toolbarPosition, 0, 0);
        if (!isInitViewData) {
            isInitViewData = true;
            anchorView.post(() -> {
                initViewStatus(anchorView.getContext());
            });
        }
    }

    /**
     * 初始化View的状态
     *
     * @param context 上下文对象
     */
    protected void initViewStatus(@NonNull Context context) {
        LogUtil.debug(getTag(), "initViewStatus:");
    }

    @Override
    public PopupWindow getWindow() {
        return mPopupWindow;
    }
}
